/*
 * Messaging service object based on com.nokia.device.messaging  Interface
 */
var messaging = null;

/*
 * Initializes messaging service object
 */
function initService(){
    try {
        messaging = nokia.device.load("messaging");
        var transactionid = messaging.setNotifier(setNotifierCb, setNotifierCbErr);
    } 
    catch (e) {
        alert(e.toString());
    }
}

/*
 * Retrieves message by specified id
 * id - message id
 */
function getMessage(id){
	var message = null;
	try{
		//id =  parseInt(id);
    	message = messaging.getMessage(id);
	}catch(e){
		alert("getMessage: " + e.toString());
	}
	return message;
}

/*
 * Callback function that called asynchronously when new message arrives.
 * It shows UI notification with message sender infornation
 */
function setNotifierCb(messageid){	
	var message = getMessage(messageid);
	if (message != null) {
		alert("New message from " + message.sender);
		listMessages();
	}
}

/*
 * Error Callback function for setNotifier.
 */
function setNotifierCbErr(err){
    alert(err.message +" "+ err.code);
}

/*
 * Callback handler for messaging.send
 * displays notification about completed sent operation
 */
function sendCb(){
	alert("Message was sent succesfully");
}

/*
 * Error Callback handler for messaging.send
 */
function sendCbErr(err){
	alert(err.toString());
}

/*
 * Sends SMS message
 * phoneNumber - recipients phone number
 * text - message text
 */
function sendSMS(phoneNumber, text){
    var message = new Object();
    //Setting the type of the message
    message.type = "SMS";
    if (phoneNumber != null && phoneNumber != "") {
        message.to = new Array();
        message.to.push(phoneNumber);
    }
    else {
        alert("Phone number is empty");
        return;
    }
    if (text != null && text != "") {
        message.body = text;
    }
    else {
        alert("Text is empty");
        return;
    }
	try {
		messaging.send(sendCb, message, null, sendCbErr);
	}catch(e){
		alert("sendSMS:" + e.toString());
	}
}

/*
 * Starts the device native message editor with predefined recipient number and message text
 * number - recipient number
 * message - message text to be sent
 * Message object is based in the following schema:
 *  {
 *    "type": String, //Supported values are "SMS" and "MMS". Defaults to "SMS".
 *    "to": [String, String, . . .],
 *    "body": String,
 *    "subject: String, //Supported by MMS only. In case of SMS this field is supported for output where in the first 64 bytes of the bodytext will be returned as subject                      //If used for SMS input it will be ignored.
 *    "cc": [String, String, . . .], //For SMS the contents of this field gets appended to tolist
 *    "attachments": [{attachment data}, {attachment data}, . . .] //Supported by MMS only
 *    }
 */
function startEditor(number, message){
    var message = {
        type: 'SMS',
        to: [number],
        body: message
    };
	try{
	    messaging.startEditor(message);
	}catch(e){
		alert(e.toString());
	}
}

/*
 * Sets specified status to message
 * id - message id
 * status - status to be set: read, unread, delete
 * delete is considered as message status, but on practice message is removed from database
 */
function setMessageStatus(id, status){
	try{
	    //var msgId = parseInt(id);
	    if (status == 'delete') {
			messaging.deleteMessage(id);
	    }
	    else {
	        var msgStatus = (status == "read" ? messaging.STATUS_READ : messaging.STATUS_UNREAD);
	        messaging.setStatus(id, msgStatus);
	    }
	}catch(e){
		alert(e.toString());
	}
}

/*
 * Callback handler for getList
 * Populates message list container with retrieved message data
 */
function listMessagesCb(retval){
    var message;
    var content = "<table border='1' width='100%'><tr><th scope='colgroup' colspan='2'><input type='checkbox' name='chAll' onClick='chALL(this.checked)'/></th><th>Sender</th><th>Message</th></tr>";
    while ((message = retval.next()) != null) {
        content += showMessage(message);
    }
    content += "</table>";
    document.getElementById("msgList").innerHTML = content;
}

/*
 * Error Callback handler for getList
 */
function listMessagesCbErr(err){
    alert(err.toString());
}

/*
 * Gets list of all messages in inbox
 */
function listMessages(){
	/*  It is possible to retrieve messages based on pattern
	 	Message Matching Pattern
		  {
		    "senders": ['sender1', 'sender2', . . .],
		    "subject": 'subject heading',
		    "start": Date, // JS Date object
		    "end": Date  
		    }
	 */
    //create filter
    var match = {};
	try {
		messaging.getList(listMessagesCb, match, messaging.SORT_BY_DATE, messaging.SORT_ASCENDING, listMessagesCbErr);
	}catch(e){
		alert(e.toString());
	}
}

/*
 * Handles single message info and produces HTML table row
 * Message Info schema:
 *    {
 *	    "message": {message data},
 *  	"sender": String,
 *	    "time":  Date,
 *	    "unread": Boolean,
 *  	"id": String // Identifies message in the message store
 *    }
 */
function showMessage(obj){
    var txt = "<tr>";
    try {
        txt += "<td width='5'><input type='checkbox' onclick='checkMain()' name='ch' value='" + obj["id"] + "'/></td>";
        txt += "<td width='5'>" + (obj["unread"] == true ? "<img src='images/img-link-email.png' border='0'/>" : "<img src='images/img-link-sms.png' border='0'/>") + "</td>";
        txt += "<td width='5'><nobr><a href='javascript:openMessage(\"" + obj["id"] + "\")'>" + obj["sender"] + "</a></nobr></td>";
 		txt += "<td>" + obj["message"]["subject"] + "</td>";
		
    } 
    catch (e) {
        alert("showMessage: " + e.toString());
    }
    txt += "</tr>";
    return txt;
}


